//
//  oldVideoViewController.m
//  laonianbangfamily
//
//  Created by 勇拓 李 on 18/3/30.
//  Copyright © 2018年 zaiyou. All rights reserved.
//

#import "oldVideoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "oldVideoFullScreenViewController.h"
#import "oldFileManager.h"

@interface oldVideoViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, oldVideoViewDelegate>

@property (nonatomic, strong) UIImagePickerController * pickerController;

@property (nonatomic, strong) AVPlayer * player;

@property (nonatomic, assign) BOOL isVideo;

@property (nonatomic, strong) UIImageView * showImageView;
@property (weak, nonatomic) IBOutlet UIButton *btn;

@property (nonatomic, strong)oldVideoView *videoView;

@end

@implementation oldVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"拍摄录像";
    
    _isVideo = YES;
    
    [self setupUI];
    
    UIButton *rightbutton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 20)];
    
    //[leftbutton setBackgroundColor:[UIColor blackColor]];
    
    [rightbutton setTitle:@"保存" forState:UIControlStateNormal];
    
    [rightbutton addTarget:self action:@selector(rightbtnTapped:) forControlEvents:UIControlEventTouchDown];
    
    UIBarButtonItem *rightitem = [[UIBarButtonItem alloc]initWithCustomView:rightbutton];
    
    self.navigationItem.rightBarButtonItem = rightitem;
    
    [self initVideoView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initVideoView
{
    if (_url) {
        if ([_videoView superview]) {
            [_videoView removeFromSuperview];
        }
        
        _videoView = [[oldVideoView alloc] initByType:VideoLocal url:_url fillType:VideoFill];
        _videoView.frame = CGRectMake((SCREEN_WIDTH - 300)/2, 20, 300, 400);
        _videoView.delegate = self;
        [self.view addSubview:_videoView];
    }
}

- (void)rightbtnTapped:(id)sender
{
    [self.delegate videoComplete:_url];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString * mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) { //如果是拍照
//        UIImage * image;
//        //如果允许编辑则获得编辑后的照片，否则获取原始照片
//        if (_pickerController.allowsEditing) {
//            image = [info objectForKey:UIImagePickerControllerEditedImage];//获取编辑后的照片
//        } else {
//            image = [info objectForKey:UIImagePickerControllerOriginalImage];//获取原始照片
//        }
//        
//        [self.showImageView setImage:image];
//        
//        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//保存到相簿
        
    } else if([mediaType isEqualToString:(NSString *)kUTTypeMovie]){ //如果是录制视频
        NSURL * url = [info objectForKey:UIImagePickerControllerMediaURL];
        NSString * urlStr = [url path];
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
            //保存视频到相簿，注意也可以使用ALAssetsLibrary来保存
            UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        }
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    NSLog(@"放弃");
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark - 点击方法
- (void)clickButton:(UIButton *)sender{
    
    [self presentViewController:self.pickerController animated:YES completion:nil];
}

#pragma mark - delegate
- (void)touchedFullScreen:(NSString *)url type:(oldVideoType)type
{
    oldVideoFullScreenViewController *vc = [oldVideoFullScreenViewController new];
    vc.url = url;
    vc.type = type;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 自定义方法
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error) {
        NSLog(@"保存视频过程中发生错误，错误信息:%@",error.localizedDescription);
    } else {
        NSLog(@"视频保存成功");
        
        if (_url) {
            [oldFileManager removeFileByPath:_url];
        }
        
        _url = videoPath;
        
        [self initVideoView];
    }
}

- (void)setupUI{
    
//    [self.view addSubview:self.showImageView];
    
    _btn.layer.cornerRadius = 6.f;
    
    [_btn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
}

- (UIImagePickerController *)pickerController{
    if (!_pickerController) {
        _pickerController = [[UIImagePickerController alloc] init];
        //设置_pickerController的来源，这里设置为摄像头。
        /*
         UIImagePickerControllerSourceTypePhotoLibrary：照片库
         ，默认值
         UIImagePickerControllerSourceTypeCamera：摄像头
         UIImagePickerControllerSourceTypeSavedPhotosAlbum：相
         */
        _pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        //设置摄像头类型
        /*
         UIImagePickerControllerCameraDeviceRear,//后置摄像头
         UIImagePickerControllerCameraDeviceFront //前置摄像头
         */
        _pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
        if (_isVideo) {//设置媒体类型为视频，默认为kUTTypeImage；
            _pickerController.mediaTypes = @[(NSString *)kUTTypeMovie];
            _pickerController.videoQuality = UIImagePickerControllerQualityTypeMedium;
            _pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
            
        }else{//设置摄像头捕获模式为 UIImagePickerControllerCameraCaptureModePhoto（默认就是）
            
            _pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        }
        
        _pickerController.allowsEditing = YES; // 允许编辑
        _pickerController.delegate = self; //设置代理，检测操作
    }
    return _pickerController;
}

- (UIImageView *)showImageView{
    if (!_showImageView) {
        _showImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 375, self.view.bounds.size.height-100)];
        _showImageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _showImageView;
}

@end
